import React, { useState, useEffect } from 'react';
import { Input, Button, Alert, Spin, Tooltip } from 'antd';
import { 
  CheckCircleOutlined, 
  CloseCircleOutlined, 
  LoadingOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import { ValidationResult, LLMProvider } from '../types/index';
import { ServiceManager } from '../services/ServiceManager';

interface ApiKeyValidatorProps {
  provider: LLMProvider;
  value?: string;
  baseURL?: string;
  onChange?: (value: string) => void;
  onValidationChange?: (result: ValidationResult | null) => void;
  disabled?: boolean;
  placeholder?: string;
  autoValidate?: boolean; // 是否自动验证
  validateDelay?: number; // 验证延迟（毫秒）
}

export const ApiKeyValidator: React.FC<ApiKeyValidatorProps> = ({
  provider,
  value = '',
  baseURL,
  onChange,
  onValidationChange,
  disabled = false,
  placeholder = "请输入 API Key",
  autoValidate = true,
  validateDelay = 1000
}) => {
  const [validationResult, setValidationResult] = useState<ValidationResult | null>(null);
  const [isValidating, setIsValidating] = useState(false);
  const [validationTimer, setValidationTimer] = useState<number | null>(null);

  const serviceManager = ServiceManager.getInstance();

  // 手动验证
  const validateApiKey = async () => {
    if (!value || !value.trim()) {
      const emptyResult: ValidationResult = {
        isValid: false,
        error: {
          code: 'EMPTY_API_KEY',
          message: 'API Key 不能为空',
          suggestion: '请输入有效的 API Key'
        }
      };
      setValidationResult(emptyResult);
      onValidationChange?.(emptyResult);
      return;
    }

    setIsValidating(true);
    
    try {
      const result = await serviceManager.validationService.validateApiKey(
        provider,
        value.trim(),
        baseURL
      );
      
      setValidationResult(result);
      onValidationChange?.(result);
    } catch (error) {
      const errorResult: ValidationResult = {
        isValid: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: '验证过程中发生错误',
          suggestion: '请检查网络连接并重试'
        }
      };
      setValidationResult(errorResult);
      onValidationChange?.(errorResult);
    } finally {
      setIsValidating(false);
    }
  };

  // 输入值变化处理
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = e.target.value;
    onChange?.(newValue);

    // 清除之前的验证结果
    if (validationResult) {
      setValidationResult(null);
      onValidationChange?.(null);
    }

    // 自动验证
    if (autoValidate && newValue.trim()) {
      // 清除之前的计时器
      if (validationTimer) {
        clearTimeout(validationTimer);
      }

      // 设置新的计时器
      const timer = setTimeout(() => {
        validateApiKey();
      }, validateDelay);
      
      setValidationTimer(timer);
    }
  };

  // 清理计时器
  useEffect(() => {
    return () => {
      if (validationTimer) {
        clearTimeout(validationTimer);
      }
    };
  }, [validationTimer]);

  // 获取输入框状态
  const getInputStatus = (): "error" | "warning" | undefined => {
    if (isValidating) return undefined;
    if (!validationResult) return undefined;
    return validationResult.isValid ? undefined : "error";
  };

  // 获取验证图标
  const getValidationIcon = () => {
    if (isValidating) {
      return <LoadingOutlined className="text-blue-500" />;
    }
    
    if (!validationResult) {
      return null;
    }

    return validationResult.isValid ? (
      <CheckCircleOutlined className="text-green-500" />
    ) : (
      <CloseCircleOutlined className="text-red-500" />
    );
  };

  // 渲染验证结果消息
  const renderValidationMessage = () => {
    if (!validationResult || isValidating) return null;

    if (validationResult.isValid) {
      return (
        <Alert
          message="验证成功"
          description={
            <div>
              <div>API Key 有效</div>
              {validationResult.metadata?.accountInfo && (
                <div className="text-xs mt-1 text-gray-600">
                  账户信息已确认
                </div>
              )}
            </div>
          }
          type="success"
          showIcon
        />
      );
    } else {
      return (
        <Alert
          message="验证失败"
          description={
            <div>
              <div>{validationResult.error?.message}</div>
              {validationResult.error?.suggestion && (
                <div className="text-xs mt-1 font-medium">
                  建议: {validationResult.error.suggestion}
                </div>
              )}
            </div>
          }
          type="error"
          showIcon
          action={
            <Button size="small" onClick={validateApiKey}>
              重试
            </Button>
          }
        />
      );
    }
  };

  return (
    <div className="space-y-2">
      <div className="flex items-center gap-2">
        <Input.Password
          value={value}
          onChange={handleInputChange}
          placeholder={placeholder}
          disabled={disabled}
          status={getInputStatus()}
          suffix={getValidationIcon()}
          iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
        />
        
        {!autoValidate && (
          <Tooltip title="验证 API Key">
            <Button
              icon={isValidating ? <LoadingOutlined /> : <ExclamationCircleOutlined />}
              onClick={validateApiKey}
              loading={isValidating}
              disabled={disabled || !value.trim()}
              type="default"
            >
              验证
            </Button>
          </Tooltip>
        )}
      </div>

      {isValidating && (
        <div className="flex items-center gap-2 text-sm text-gray-600">
          <Spin size="small" />
          <span>正在验证 API Key...</span>
        </div>
      )}

      {renderValidationMessage()}
    </div>
  );
};